package com.hdsx.restful.support;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.Statement;
import java.util.Map;
import java.util.logging.Logger;

import javax.sql.DataSource;

import org.springframework.jdbc.datasource.lookup.AbstractRoutingDataSource;

import com.hdsx.restful.base.DBSwitch;
import com.jolbox.bonecp.BoneCPDataSource;

public class DynamicDataSource extends AbstractRoutingDataSource {

	@Override
	protected Object determineCurrentLookupKey() {
		// TODO Auto-generated method stub
		String dataSourceName = DBSwitch.GISDB;
		if (dataSourceName == null) {
			return "dataSource";
		} else {
			return dataSourceName;
		}
	}

	@Override
	public void setTargetDataSources(Map<Object, Object> targetDataSources) {
		// TODO Auto-generated method stub
		DataSource dataSource = (DataSource) targetDataSources
				.get("defaultTargetDataSource");
		try {
			Connection conn = dataSource.getConnection();
			Statement statament = conn.createStatement();
			ResultSet rs = statament
					.executeQuery("select * from CONFIG WHERE ISCURRENTVERSION='1' AND TYPE ='1' ");
			BoneCPDataSource boneCP = null;
			if (rs.next()) {
				String username = rs.getString("USERNAME");
				String password = rs.getString("PASSWORD");
				String host = rs.getString("HOST");
				String sid=rs.getString("SID");
				boneCP = new BoneCPDataSource();
				boneCP.setUsername(username);
				boneCP.setPassword(password);
				boneCP.setJdbcUrl("jdbc:oracle:thin:@"+host+":1521:"+sid);
				boneCP.setDriverClass("oracle.jdbc.driver.OracleDriver");
				targetDataSources.put(DBSwitch.GISDB, boneCP);
			/*	IPropertySet prop = initPropertySet("", "sde:oracle11g:local" ,"", username, password, "sde.DEFAULT");
				DBHandler.getInstance().initDataSource(prop);
				AoDao dao = new AoDaoImpl(prop);
				DaoSupport.attach(DBSwitch.GISDB, dao);*/
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		super.setTargetDataSources(targetDataSources);
		super.afterPropertiesSet();
	}

	public Logger getParentLogger() throws SQLFeatureNotSupportedException {
		return null;
	}

}
